<?php
declare (strict_types=1);

namespace app\listener;

use app\common\model\Consulting;
use app\common\model\ConsultingMessage;
use app\common\model\Member;
use app\common\service\MiniProgramMessageService;
use app\index\service\MessageSendService;

class ConsultingEnded
{
    /**
     * 咨询结束 事件监听处理
     *
     * @return mixed
     */
    public function handle(Consulting $consulting)
    {
        // 触发了咨询结束事件

        // 判断是否已经发送过
        $repeat = ConsultingMessage::where('consultingId', $consulting->id)
            ->where('messageType', ConsultingMessage::COMMENT)
            ->find();
        if ($repeat) {
            return;
        }

        if (is_id($consulting->lawyerId)) {

            // 发评价消息给用户
            $content = [
                'consultingId' => $consulting->id,
                'lawyerId' => $consulting->lawyerId,
                'level' => null,
            ];
            $this->getMessageSendService()->sendSystemMessage($consulting, 0, ConsultingMessage::COMMENT, $content);

            // 发小程序订阅消息给用户
            $lawyerName = Member::where('id', $consulting->lawyerId)->value('realname') . '律师';
            $this->getMiniProgramMessageService()->messageRemindComment($consulting->memberId, $consulting->ask, $lawyerName);

            // 发系统消息给律师
            $content = [
                'templates' => [
                    [
                        'type' => 'text', 'red' => '102', 'text' => '服务已经结束，评价卡片已发送给用户可引导用户进行好评或红包感谢',
                    ]
                ],
            ];
            $this->getMessageSendService()->sendSystemMessage($consulting, $consulting->lawyerId, ConsultingMessage::SYSTEM, $content);

        }
    }

    private function getMessageSendService(): MessageSendService
    {
        return app(MessageSendService::class);
    }

    private function getMiniProgramMessageService(): MiniProgramMessageService
    {
        return app(MiniProgramMessageService::class);
    }
}
